import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateCommunityDto } from './dto/create-community.dto';
import { UpdateCommunityDto } from './dto/update-community.dto';
import { CreatePostDto } from './dto/create-post.dto';
import { Post } from './entities/post.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';
import { CreateCommentDto } from './dto/create-comment.dto';
import { Comment } from './entities/comment.entity';
import { PostLike } from './entities/postLikes.entity';
import { User } from 'src/user/entities/user.entity';
import { CommentLikes } from './entities/commentLikes.entity';
import { DailyCommentStats } from 'src/statistic/entities/dailyCommentStats.entity';

@Injectable()
export class CommunityService {
  @InjectRepository(Post)
  private readonly postRepository: Repository<Post>;

  @InjectRepository(User)
  private readonly userRepository: Repository<User>;

  @InjectRepository(Comment)
  private readonly commentRepository: Repository<Comment>;

  @InjectRepository(PostLike)
  private readonly postLikeRepository: Repository<PostLike>;

  @InjectRepository(CommentLikes)
  private readonly commentLikeRepository: Repository<CommentLikes>;

  @InjectRepository(DailyCommentStats)
  private dailyCommentStatsRepository: Repository<DailyCommentStats>;

  // 发布帖子
  async createPost(createPostDto: CreatePostDto) {
    const user = await this.userRepository.findOne({
      where: { id: createPostDto.userId },
    });

    const post = this.postRepository.create({
      title: createPostDto.title,
      content: createPostDto.content,
      user: user,
    });

    return await this.postRepository.save(post);
  }

  // 删除自己发的帖子
  async deletePost(postId: number, userId: number) {
    const post = await this.postRepository.findOne({
      where: { id: postId, user: { id: userId } },
    });
    if (!post) {
      throw new BadRequestException('您没有权限删除此帖子');
    }

    return this.postRepository.remove(post);
  }

  // 按名字模糊查询帖子
  async getPostByName(title: string, pageNo: number, pageSize: number) {
    const skipCount = (pageNo - 1) * pageSize;

    // 条件对象
    const condition: Record<string, any> = {};

    if (title) {
      condition.title = Like(`%${title}%`);
    }

    const [posts, totalCount] = await this.postRepository.findAndCount({
      relations: ['user', 'comments'],
      skip: skipCount,
      take: pageSize,
      where: condition,
      order: { createTime: 'DESC' },
    });

    return {
      posts,
      totalCount,
    };
  }

  // 查看帖子详情
  async getPostDetail(postId: number, userId: number) {
    // 增加浏览量
    await this.postRepository.increment({ id: postId }, 'views', 1);

    // 获取帖子详情，包括用户信息和评论
    const post = await this.postRepository.findOne({
      where: { id: postId },
      relations: ['user', 'comments', 'comments.user'],
    });

    if (!post) {
      throw new BadRequestException('帖子不存在');
    }

    // 查询当前用户是否对该帖子点过赞
    const existingLike = await this.postLikeRepository.findOne({
      where: { post: { id: postId }, user: { id: userId } },
    });

    return {
      ...post,
      liked: !!existingLike, // 如果点过赞，则返回 true，否则 false
    };
  }

  // 用户评论帖子
  async createComment(createCommentDto: CreateCommentDto) {
    const user = await this.userRepository.findOne({
      where: { id: createCommentDto.userId },
    });
    // 发布一条评论添加到dailyCommentStatsRepository
    const today = new Date().toISOString().split('T')[0]; // 获取当前日期 (YYYY-MM-DD)

    let stats = await this.dailyCommentStatsRepository.findOne({
      where: { date: today },
    });

    if (!stats) {
      // 如果当天没有统计记录，创建新记录
      stats = this.dailyCommentStatsRepository.create({
        date: today,
        commentCount: 1,
      });
    } else {
      // 如果已有统计记录，更新评论数
      stats.commentCount += 1;
    }

    await this.dailyCommentStatsRepository.save(stats);
    const comment = this.commentRepository.create({
      content: createCommentDto.content,
      user,
      post: { id: createCommentDto.postId },
      parentId: createCommentDto.parentId || null,
    });

    return await this.commentRepository.save(comment);
  }

  // 点赞/取消点赞 帖子
  async togglePostLike(postId: number, userId: number) {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) return { message: '用户不存在', liked: false };

    try {
      const existingLike = await this.postLikeRepository.findOne({
        where: { post: { id: postId }, user: { id: userId } },
      });

      if (existingLike) {
        // 取消点赞
        await this.postLikeRepository.remove(existingLike);
        await this.postRepository.decrement({ id: postId }, 'likes', 1);
        return { message: '取消点赞成功', liked: false };
      }

      // 新增点赞
      const newLike = this.postLikeRepository.create({
        user,
        post: { id: postId },
      });
      await this.postLikeRepository.save(newLike);
      await this.postRepository.increment({ id: postId }, 'likes', 1);

      return { message: '点赞成功', liked: true };
    } catch (error) {
      if (error.code === '23505') {
        return { message: '已经点赞过该帖子', liked: true };
      }
      throw error;
    }
  }

  // 点赞/取消点赞 评论
  async toggleCommentLike(commentId: number, userId: number) {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) return { message: '用户不存在', liked: false };

    try {
      const existingLike = await this.commentLikeRepository.findOne({
        where: { comment: { id: commentId }, user: { id: userId } },
      });

      if (existingLike) {
        // 取消点赞
        await this.commentLikeRepository.remove(existingLike);
        await this.commentRepository.decrement({ id: commentId }, 'likes', 1);
        return { message: '取消点赞成功', liked: false };
      } else {
        // 新增点赞
        const newLike = this.commentLikeRepository.create({
          user,
          comment: { id: commentId },
        });
        await this.commentLikeRepository.save(newLike);
        await this.commentRepository.increment({ id: commentId }, 'likes', 1);
        return { message: '点赞成功', liked: true };
      }
    } catch (error) {
      if (error.code === '23505') {
        return { message: '已经点赞过该评论', liked: true };
      }
    }
  }

  // 管理员删除帖子
  async deletePostAdmin(postId: number) {
    console.log(typeof postId);

    const post = await this.postRepository.findOne({
      where: { id: postId },
      relations: ['comments'],
    });
    if (!post) {
      throw new BadRequestException('帖子不存在');
    }
    await this.postRepository.remove(post);
  }

  // 管理员删除评论
  async deleteCommentAdmin(commentId: number) {
    const comment = await this.commentRepository.findOne({
      where: { id: commentId },
    });
    if (!comment) {
      throw new BadRequestException('评论不存在');
    }
    return this.commentRepository.remove(comment);
  }
  // 获取评论列表
  async getCommentList(content: string, pageNo: number, pageSize: number) {
    const skipCount = (pageNo - 1) * pageSize;
    const condition: Record<string, any> = {};
    if (content) {
      condition.content = Like(`%${content}%`);
    }
    const [comments, totalCount] = await this.commentRepository.findAndCount({
      relations: ['user', 'post'],
      skip: skipCount,
      take: pageSize,
      where: condition,
      order: { createTime: 'DESC' },
    });
    return { comments, totalCount };
  }
}
